// #include "LinkTree.h"
// #include <stdio.h>
// #include <MyString.h>
// #define GetNode(str) FindLinkTreeNode(tree,(void*)str,IsNameEqual)

// void Print(void *ptr)
// {
//     printf("%s\n",(char*)ptr);
// }

// bool IsNameEqual(void *ptr1,void *ptr2)
// {
//     INSERTSTR(str,(char*)ptr1);
//     return IsEqual(&str,(char*)ptr2);
// }

// TNode *FindNodeByPath(LTree *tree,const char* path)
// {
//     MyStrList strList = Split(path,"/");
//     TNode *target = GetTreeRoot(tree);
//     for(int i = 0; i < strList.len; i++)
//     {
//         target = FindChildNode(target,(void*)strList.StringList[i].string,IsNameEqual);
//         if(target == NULL)
//         {
//             printf("没找到!\n");
//             return NULL;
//         }
//     }
//     return target;
// }




// int main()
// {
//     LTree *tree = InitLinkTree();

//     TNode *class1 = CreateTreeNode("251");
//     TNode *class2 = CreateTreeNode("252");
//     ConnectBranch(GetTreeRoot(tree),class1);
//     ConnectBranch(GetTreeRoot(tree),class2);
    
//     ConnectBranch(GetNode("251"),CreateTreeNode("第一组"));
//     ConnectBranch(GetNode("251"),CreateTreeNode("第二组"));
//     ConnectBranch(GetNode("252"),CreateTreeNode("第一组"));
//     ConnectBranch(GetNode("252"),CreateTreeNode("第二组"));

//     ConnectBranch(FindNodeByPath(tree,"251/第一组"),CreateTreeNode("张三"));

//     ConnectBranch(FindNodeByPath(tree,"251/第二组"),CreateTreeNode("李四"));

//     ConnectBranch(FindNodeByPath(tree,"252/第一组"),CreateTreeNode("王五"));

//     ConnectBranch(FindNodeByPath(tree,"252/第二组"),CreateTreeNode("六子"));

//     TravelTree(tree,Print);
//     ClearLinkTree(tree);
//     return 0;
// }

#include "LinkTree.h"
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <MyString.h>

void Print(void* ptr)
{
    printf("%s\n",(char*)ptr);
}

void ExploreDirectory(const char *path,TNode *node)
{
    DIR *d = opendir(path);
    if(d == NULL)
        return;

    struct dirent *e = NULL;
    while((e = readdir(d)) != NULL)
    {
        if(strcmp(e->d_name,".")== 0 || strcmp(e->d_name,"..") == 0)
        {
            continue;
        }

        TNode *fileNode = CreateTreeNode(GetString(e->d_name).string);
        ConnectBranch(node,fileNode);
        if(e->d_type == 4)
        {
            char filePath[1024] = {0};
            strcpy(filePath,path);
            strcat(filePath,"/");
            strcat(filePath,e->d_name);
            ExploreDirectory(filePath,fileNode);
        }
    }
    closedir(d);
}

int main(int argc,char* argv[])
{
    if(argc != 1 && argc != 2)
    {
        printf("参数输入错误!\n");
        return -1;
    }
    char *path = NULL;
    if(argc == 1)
    {
        path = "./";
    }
    else
    {
        path = argv[1];
    }

    LTree *tree = InitLinkTree();

    TNode *pathNode = CreateTreeNode(path);
    ConnectBranch(GetTreeRoot(tree),pathNode);

    ExploreDirectory(path,pathNode);

    TravelTree(tree,Print);
    ClearLinkTree(tree);

    return 0;
}